import 'package:permission_handler/permission_handler.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../public.dart';
import 'components/search_item.dart';

class SearchPage extends StatefulWidget {
  @override
  _SearchPageState createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage>
    with AutomaticKeepAliveClientMixin {
  String searchKey = "";

  void checkAuth() async {
    bool status = await PermissionManager.checkPermission(Permission.storage);

    if (status) {
      DatabaseHelper.internal();
      DatabaseHelper().initDb();
    } else {
      Future.delayed(Duration.zero, () {
        showDialog(
          context: context,
          builder: (ctx) => CustomDialog(
            title: "这里需要写入文件权限来保存数据，请点击确认按钮手动授予写入文件权限。",
            confirm: () {
              openAppSettings();
              Navigator.pop(context);
            },
          ),
        );
      });
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    checkAuth();
  }

  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

//  HideAlways
  @override
  Widget build(BuildContext context) {
    super.build(context);
    // TODO: implement build
    return Container(
        color: Color(0xFF111427),
        child: ProviderWidget<SearchBookModel>(
            model: SearchBookModel(Provider.of<ThemeModel>(context)),
            onModelReady: (model) async => model.initData(),
            builder: (context, model, child) {
              return Scaffold(
                  floatingActionButton: Container(
                    width: ScreenUtil().setWidth(150),
                    height: ScreenUtil().setWidth(100),
                    child: MaterialButton(
                      onPressed: () {
                        if (model.searchKey == "") return;
                        if (model.ruleIndex < model.rules.length - 1) {
                          model.ruleIndex++;
                        } else {
                          model.ruleIndex = 0;
                        }
                        model.refresh(init: true);
                      },
                      color: Color(0xFF333333),
                      shape: RoundedRectangleBorder(
                          side: BorderSide.none,
                          borderRadius: BorderRadius.all(Radius.circular(50))),
                      child: Center(
                        child: Text(
                          "换源",
                          style: TextStyle(
                              fontSize: ScreenUtil().setSp(20),
                              color: Color(0xFFFFFFFF),
                              fontWeight: FontWeight.w900),
                          softWrap: false,
                          textAlign: TextAlign.center,
                        ),
                      ),
                    ),
                  ),
                  body: () {
                    return WillPopScope(
                      onWillPop: _willPopHandle,
                      child: SafeArea(
                        child: Column(
                          children: <Widget>[
                            Container(
                              color: model.themeModel.customThemeData.mainColor,
                              height: ScreenUtil().setHeight(70),
                              padding: EdgeInsets.fromLTRB(
                                ScreenUtil().setWidth(20),
                                0,
                                ScreenUtil().setWidth(20),
                                0,
                              ),
                              child: Row(
                                children: <Widget>[
                                  Expanded(
                                    flex: 14,
                                    child: Container(
                                      decoration: new BoxDecoration(
                                        color: model.themeModel.customThemeData
                                            .mainBackgroundColor,
                                        borderRadius: new BorderRadius.all(
                                            new Radius.circular(20.0)),
                                      ),
                                      alignment: Alignment.center,
                                      height: ScreenUtil().setHeight(50),
                                      padding: EdgeInsets.fromLTRB(
                                        ScreenUtil().setWidth(20),
                                        0.0,
                                        ScreenUtil().setWidth(20),
                                        0.0,
                                      ),
                                      child: TextField(
                                        onSubmitted: (text) {
                                          model.searchKey = text;
                                          if (model.searchKey == "") {
                                            return;
                                          }
                                          model.refresh(init: true);
                                        },
                                        autofocus: true,
                                        textInputAction: TextInputAction.search,
                                        cursorColor: model.themeModel
                                            .customThemeData.mainUnActiveColor,
                                        //设置光标
                                        decoration: InputDecoration(
                                          //输入框decoration属性
                                          contentPadding: EdgeInsets.symmetric(
                                              vertical:
                                                  ScreenUtil().setHeight(16),
                                              horizontal:
                                                  ScreenUtil().setHeight(2)),
                                          border: InputBorder.none,
                                          icon: new Icon(
                                            IconFonts.search,
                                            size: ScreenUtil().setSp(28,
                                                allowFontScalingSelf: true),
                                            color: model.themeModel
                                                .customThemeData.mainTextColor
                                                .withOpacity(0.5),
                                          ),
                                          hintText: "请输入书名",
                                          hintStyle: new TextStyle(
                                            fontSize: ScreenUtil().setSp(26,
                                                allowFontScalingSelf: true),
                                            color: model.themeModel
                                                .customThemeData.mainTextColor
                                                .withOpacity(0.5),
                                          ),
                                        ),
                                        style: new TextStyle(
                                          fontSize: ScreenUtil().setSp(26,
                                              allowFontScalingSelf: true),
                                          color: model.themeModel
                                              .customThemeData.mainTextColor
                                              .withOpacity(0.5),
                                        ),
                                      ),
                                    ),
                                  ),
                                  Expanded(
                                    flex: 2,
                                    child: Container(
                                      child: Center(
                                        child: MaterialButton(
                                            padding: EdgeInsets.all(0),
                                            child: Text(
                                              "取消",
                                              style: new TextStyle(
                                                color: model
                                                    .themeModel
                                                    .customThemeData
                                                    .mainTextColor
                                                    .withOpacity(0.5),
                                              ),
                                            ),
                                            onPressed: () {
                                              AppConfig.router.pop(context);
                                            }),
                                      ),
                                    ),
                                  )
                                ],
                              ),
                            ),
                            Container(
                              color: model.themeModel.customThemeData.mainColor,
                              height: ScreenUtil().setHeight(1334 - 70) -
                                  ScreenUtil.statusBarHeight -
                                  ScreenUtil.bottomBarHeight,
                              child: () {
                                if (model.busy) {
                                  return Container(
                                    color: model
                                        .themeModel.customThemeData.mainColor,
                                    child: ViewStateBusyWidget(),
                                  );
                                } else if (model.error) {
                                  return ViewStateWidget(
                                      onPressed: model.initData);
                                } else if (model.empty) {
                                  return ViewStateEmptyWidget(
                                      buttonText: Text(
                                        "没有找到想要的书籍？试试右下角的换源吧！",
                                        style: TextStyle(
                                          fontSize: ScreenUtil().setSp(24,
                                              allowFontScalingSelf: true),
                                          color: model.themeModel
                                              .customThemeData.mainTextColor
                                              .withOpacity(0.5),
                                        ),
                                      ),
                                      onPressed: model.refresh);
                                }
                                return model.searchKey == ""
                                    ? _buildRecommend(model)
                                    : SmartRefresher(
                                        enablePullDown: true,
                                        enablePullUp: true,
                                        header: MaterialClassicHeader(
                                          color: Colors.white,
                                          backgroundColor: Colors.black54,
                                        ),
                                        footer: CustomFooter(
                                          loadStyle: LoadStyle.ShowWhenLoading,
                                          height: 60,
                                          builder: (BuildContext context,
                                              LoadStatus mode) {
                                            Widget body;
                                            if (mode == LoadStatus.idle) {
                                              body = Text(
                                                "上拉加载",
                                                style: TextStyle(
                                                  color: model
                                                      .themeModel
                                                      .customThemeData
                                                      .mainTextColor
                                                      .withOpacity(0.5),
                                                ),
                                              );
                                            } else if (mode ==
                                                LoadStatus.loading) {
                                              body = ViewStateLoadingWidget(
                                                color: model
                                                    .themeModel
                                                    .customThemeData
                                                    .mainTextColor
                                                    .withOpacity(0.5),
                                              );
                                            } else if (mode ==
                                                LoadStatus.failed) {
                                              body = Text("加载失败!",
                                                  style: TextStyle(
                                                    color: model
                                                        .themeModel
                                                        .customThemeData
                                                        .mainTextColor
                                                        .withOpacity(0.5),
                                                  ));
                                            } else if (mode ==
                                                LoadStatus.canLoading) {
                                              body = Text("松手,加载更多!",
                                                  style: TextStyle(
                                                    color: model
                                                        .themeModel
                                                        .customThemeData
                                                        .mainTextColor
                                                        .withOpacity(0.5),
                                                  ));
                                            } else {
                                              body = Text("没有更多数据了!",
                                                  style: TextStyle(
                                                    color: model
                                                        .themeModel
                                                        .customThemeData
                                                        .mainTextColor
                                                        .withOpacity(0.5),
                                                  ));
                                            }
                                            return Container(
                                              height: 55.0,
                                              color: model.themeModel
                                                  .customThemeData.mainColor,
                                              child: Center(child: body),
                                            );
                                          },
                                        ),
                                        controller: _refreshController,
                                        onRefresh: () async {
                                          //我在下拉刷新时执行
                                          if (model.searchKey == "") {
                                            _refreshController
                                                .refreshCompleted();
                                            return;
                                          }
                                          await model.refresh();
                                          // if failed,use refreshFailed()
                                          _refreshController.refreshCompleted();
                                        },
                                        onLoading: () async {
                                          //我在上滑加载更多时执行
                                          if (!model.finish) {
                                            if (model.searchKey == "") {
                                              _refreshController
                                                  .refreshCompleted();
                                              return;
                                            }
                                            await model.loadMore();
                                            _refreshController.loadComplete();
                                          } else {
                                            _refreshController.loadNoData();
                                          }
                                        },
                                        child: ListView.builder(
                                          itemBuilder: (BuildContext context,
                                              int index) {
                                            return SearchItem(
                                              item: model.list[index],
                                              index: index,
                                              model: model,
                                              list: model.list,
                                            );
                                          },
                                          itemCount: model.list.length,
                                          shrinkWrap: true,
                                        ),
                                      );
                              }(),
                            )
                          ],
                        ),
                      ),
                    );
                  }());
            }));
  }

  Widget _buildRecommend(SearchBookModel model) {
    return Container(
      child: Column(
        children: <Widget>[
          Container(
            alignment: Alignment.centerLeft,
            margin: EdgeInsets.fromLTRB(
              ScreenUtil().setWidth(750 * 0.05),
              ScreenUtil().setWidth(750 * 0.05),
              ScreenUtil().setWidth(750 * 0.05),
              ScreenUtil().setHeight(10),
            ),
            child: Text(
              "大家都在搜",
              textAlign: TextAlign.left,
              style: TextStyle(
                color: model.themeModel.customThemeData.mainTextColor
                    .withOpacity(0.7),
                fontFamily: "xiaowei",
                fontSize: ScreenUtil().setSp(30, allowFontScalingSelf: true),
              ),
            ),
          ),
          Container(
            alignment: Alignment.centerLeft,
            margin: EdgeInsets.fromLTRB(
              ScreenUtil().setWidth(750 * 0.05),
              0,
              ScreenUtil().setWidth(750 * 0.05),
              ScreenUtil().setWidth(750 * 0.05),
            ),
            child: Wrap(
              children: _buildRecommendList(model),
            ),
          )
        ],
      ),
    );
  }

  List<Widget> _buildRecommendList(SearchBookModel model) {
    List<Widget> _list = [];
    for (int index = 0; index < model.hot.length; index++) {
      _list.add(Container(
        margin: EdgeInsets.fromLTRB(
          0,
          0,
          ScreenUtil().setWidth(15),
          ScreenUtil().setHeight(15),
        ),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(100)),
            border: Border.all()),
        padding: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(20),
          ScreenUtil().setWidth(10),
          ScreenUtil().setWidth(20),
          ScreenUtil().setWidth(10),
        ),
        child: Text(model.hot[index].name,
            textAlign: TextAlign.center,
            style: TextStyle(
              color: model.themeModel.customThemeData.mainTextColor
                  .withOpacity(0.7),
              fontSize: ScreenUtil().setSp(24, allowFontScalingSelf: true),
            )),
      ));
    }
    return _list;
  }

  Widget _appBar(SearchBookModel model) {
    return PreferredSize(
        preferredSize: Size.fromHeight(ScreenUtil().setHeight(88)),
        child: AppBar(
          backgroundColor: model.themeModel.customTheme.main,
          bottom: PreferredSize(
            preferredSize: Size.fromHeight(ScreenUtil().setHeight(88)),
            child: Container(),
          ),
          title: Container(),
          automaticallyImplyLeading: false,
        ));
  }

  Future<bool> _willPopHandle() async {
    return Future.value(true);
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
